package com.qf.java2201.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.qf.java2201.dto.BackExcelDto;
import com.qf.java2201.pojo.Back;
import com.qf.java2201.service.BackService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yjl
 * @version 1.0
 * @date 2022/4/28 16:02
 */
@Component
@Scope("prototype")
public class BackListener extends AnalysisEventListener<BackExcelDto>{
    @Autowired
    private BackService backService;

    private List<Back> backs =new ArrayList<>();

    @Override
    public void invoke(BackExcelDto data, AnalysisContext context) {
    //easyexcel 把读到的数据 封装到dto里
        System.out.println(data);

        //创建一个pojo
        Back back = new Back();

        //把dto数据封装到 pojo中
        BeanUtils.copyProperties(data,back);

        // 每读取一行 excel 都会得到 一个 dto  ，把dto转为 pojo 然后放入 集合
        backs.add(back);

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        System.out.println(backs);
        //把集合数据存入数据库
        backService.addExcele(backs);
        backs.clear();

    }
}
